<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col> -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <div class="commonMenu">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <!-- publish_status：0草稿，1发布（这个状态下看notice_status的状态）
        notice_status：0待发布，1已发布，2已结束 -->
        <el-menu-item index="">全部</el-menu-item>
        <el-menu-item index="0">草稿</el-menu-item>
        <el-menu-item index="1">待发布</el-menu-item>
        <el-menu-item index="2">已发布</el-menu-item>
        <el-menu-item index="3">已结束</el-menu-item>
      </el-menu>
    </div>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="公告标题" align="center" prop="noticeTitle"/>
      <el-table-column label="姓名（账号）" align="center" prop="creator">
        <template slot-scope="scope">
          <span>{{ scope.row.creator }}</span>
          <span>（{{ scope.row.userName }}）</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <!-- publishStatus：0草稿，1发布（这个状态下看notice_status的状态）
        noticeStatus：0待发布，1已发布，2已结束 -->
          <el-tag
            type="info"
            v-if="!scope.row.publishStatus && scope.row.noticeStatus == 0"
          >草稿
          </el-tag
          >
          <el-tag
            type="warning"
            v-if="scope.row.publishStatus && scope.row.noticeStatus == 0"
          >
            待发布
          </el-tag>
          <el-tag
            type="success"
            v-if="scope.row.publishStatus && scope.row.noticeStatus == 1"
          >
            已发布
          </el-tag>
          <el-tag
            type="danger"
            v-if="!scope.row.publishStatus && scope.row.noticeStatus == 2"
          >
            已结束
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column width="180" label="接收端" align="center" prop="receiverList">
      </el-table-column>
      <el-table-column
        label="公告时间"
        align="center"
        prop="createTime"
        width="320"
      >
        <template slot-scope="scope">
          <span
          >{{ parseTime(scope.row.startTime) }} 至
            {{ parseTime(scope.row.endTime) }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- publishStatus：0草稿，1发布（这个状态下看notice_status的状态）
        noticeStatus：0待发布，1已发布，2已结束 -->
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            v-if="
              (scope.row.publishStatus && scope.row.noticeStatus == 0) ||
              (scope.row.publishStatus && scope.row.noticeStatus == 1) ||
              (!scope.row.publishStatus && scope.row.noticeStatus == 2)
            "
            @click="handleUpdate(scope.row, 'detail')"
          >详情
          </el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            v-if="
              (scope.row.publishStatus && scope.row.noticeStatus == 0) ||
              (scope.row.publishStatus && scope.row.noticeStatus == 1)
            "
            @click="handleTakedown(scope.row)"
          >撤销
          </el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="!scope.row.publishStatus && scope.row.noticeStatus == 0"
            @click="handleUpdate(scope.row, 'edit')"
          >编辑
          </el-button
          >
          <el-button
            v-preventReClick
            v-if="!scope.row.publishStatus && scope.row.noticeStatus == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        @submit.native.prevent
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <div v-if="title === '查看公告'">
                {{ form.noticeTitle }}
              </div>
              <el-input
                v-else
                v-model="form.noticeTitle"
                placeholder="请输入公告标题"
                maxlength="40"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="startTime">
              <el-checkbox
                v-model="timePickerUse"
                :disabled="title === '查看公告'"
              >定时发送
              </el-checkbox
              >
              <el-date-picker
                :picker-options="pickerOptionsEnd"
                :disabled="!timePickerUse || title === '查看公告'"
                style="margin-left: 15px"
                v-model="form.startTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="收件人" prop="receiverList">
          <!-- 端口 -->
          <el-table :data="ports">
            <el-table-column label="端口" align="center" width="200">
              <template slot-scope="scope">
                <span
                ><el-checkbox
                  :disabled="title === '查看公告'"
                  v-model="scope.row.checked"
                  :indeterminate="scope.row.isIndeterminate"
                  @change="
                      handleCheckAllChange($event, 'ports', scope.$index)
                    "
                >{{ scope.row.keyName }}</el-checkbox
                ></span
                >
              </template>
            </el-table-column>
            <el-table-column label="角色" align="center">
              <template slot-scope="scope">
                <el-checkbox
                  :disabled="title === '查看公告'"
                  @change="
                    handleCheckedRoleChange(
                      $event,
                      'ports',
                      scope.$index,
                      index
                    )
                  "
                  v-for="(item, index) in scope.row.List"
                  v-model="item.checked"
                  :key="index"
                >{{ item.keyName }}
                </el-checkbox
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 角色 -->
          <el-table :data="roles">
            <el-table-column label="角色" align="center" width="200">
              <template slot-scope="scope">
                <span
                ><el-checkbox
                  :disabled="title === '查看公告'"
                  v-model="scope.row.checked"
                  :indeterminate="scope.row.isIndeterminate"
                  @change="
                      handleCheckAllChange($event, 'roles', scope.$index)
                    "
                >{{ scope.row.keyName }}</el-checkbox
                ></span
                >
              </template>
            </el-table-column>
            <el-table-column label="分院" align="center">
              <template slot-scope="scope">
                <el-checkbox
                  :disabled="title === '查看公告'"
                  @change="
                    handleCheckedRoleChange(
                      $event,
                      'roles',
                      scope.$index,
                      index
                    )
                  "
                  v-for="(item, index) in scope.row.List"
                  v-model="item.checked"
                  :key="index"
                >{{ item.keyName }}
                </el-checkbox
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="公告内容" prop="noticeContent">
          <div v-if="title === '查看公告'" v-html="form.noticeContent"></div>
          <wangEditor v-else :editorValue.sync="form.noticeContent"></wangEditor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="cancel"
          v-if="title == '添加公告' || title == '编辑公告'"
        >取 消
        </el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm('save')"
          v-if="title == '添加公告' || title == '编辑公告'"
        >保 存
        </el-button
        >
        <el-button @click="cancel" type="primary" v-if="title == '查看公告'"
        >关 闭
        </el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm('add')"
          v-if="title == '添加公告' || title == '编辑公告'"
        >发 送
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//TODO 只写了全局模板
import wangEditor from '@/components/Editor/wangEditor.vue'
import {
  addPost_notice,
  listPost_notice,
  updatePost_notice,
  delPost_notice,
  changePublishStatus
} from '@/api/notificationCenter/notification'
import { listRole } from '@/api/system/role'
import { listPost_branch } from '@/api/schoolOrganization/organization'
import { parseTime } from '@/utils/cc'

export default {
  components: { wangEditor },
  name: 'Post',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      pickerOptionsEnd: {
        disabledDate: (time) => {
          // 获取当前日期和时间
          const currentDate = new Date()
          currentDate.setDate(currentDate.getDate() - 1)
          const currentTime = currentDate.getTime()

          // 获取选择的日期和时间
          const selectedTime = time.getTime()

          // 比较日期和时间
          return selectedTime < currentTime;

           // 允许选择的日期和时间
        }
      },
      timePickerUse: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // level
      level: [],
      // 查询参数
      activeIndex: '',
      queryParams: {
        date: '',
        pageNum: 1,
        pageSize: 10,
        creator: undefined,
        noticeTitle: undefined,
        noticeType: 2,
        publishStatus: '',
        notice_status: ''
      },
      levels: [
        { id: 1, name: '级别一' },
        { id: 2, name: '级别二' }
      ],
      // 表单参数
      form: {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeContent: undefined,
        noticeType: 2,
        startTime: '',
        endTime: '',
        receiverList: undefined,
        publishStatus: '',
        notice_status: '',
        readStatus: false,
        remark: '',
        status: ''
      },
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: '公告标题不能为空', trigger: 'blur' }
        ],
        noticeContent: [
          { required: true, message: '公告内容不能为空', trigger: 'blur' }
        ],
        receiverList: [
          { required: true, message: '收件人不能为空', trigger: 'blur' }
        ]
      },
      roles: [
        {
          roleId: 3,
          keyName: '教师',
          checked: false,
          isIndeterminate: false,
          status: 0,
          type: 5,
          List: []
        },
        {
          roleId: 4,
          keyName: '学生',
          checked: false,
          isIndeterminate: false,
          status: 0,
          type: 5,
          List: []
        }
      ],
      ports: [
        {
          keyName: '教务端',
          checked: false,
          isIndeterminate: false,
          List: [],
          type: 1
        }
      ]
    }
  },
  created() {
    this.getList()
    this.getBranch()
    this.getRoleList()
  },
  methods: {
    parseTime,
    getBranch() {
      listPost_branch({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId
      }).then((response) => {
        this.roles.map((role) => {
          role.List = response.rows.map((item) => {
            return {
              branchId: item.branchId,
              keyName: item.branchName,
              type: 2,
              status: '0'
            }
          })
        })
      })
    },
    getRoleList() {
      listRole().then((res) => {
        this.ports.map((port) => {
          port.List = []
          res.rows.map((role) => {
            if (role.type == 1) {
              role.checked = false
              port.List.push({
                keyName: role.roleName,
                roleId: role.roleId,
                status: role.status,
                type: 5
              })
            }
          })
        })
      })
    },
    // el-menu
    handleSelect(key) {
      // <!-- publish_status：0草稿，1发布（这个状态下看notice_status的状态）
      //   notice_status：0待发布，1已发布，2已结束 -->
      if (key == '') {
        this.queryParams.publishStatus = ''
        this.queryParams.noticeStatus = ''
      } else if (key == 0) {
        this.queryParams.publishStatus = 0
        this.queryParams.noticeStatus = 0
      } else if (key == 1) {
        this.queryParams.publishStatus = 1
        this.queryParams.noticeStatus = 0
      } else if (key == 2) {
        this.queryParams.publishStatus = 1
        this.queryParams.noticeStatus = 1
      } else {
        this.queryParams.publishStatus = 0
        this.queryParams.noticeStatus = 2
      }
      this.getList()
    },
    /* 分院-全选 */
    /* 角色-全选 */
    handleCheckAllChange(val, datakey, portIndex) {
      this[datakey][portIndex].List.map((item) => {
        item.checked = val
      })
      this[datakey][portIndex].isIndeterminate = false
    },
    handleCheckedRoleChange(value, datakey, portIndex, roleIndex) {
      this.$set(
        this[datakey][portIndex].List,
        roleIndex,
        this[datakey][portIndex].List[roleIndex]
      )
      this.$forceUpdate()
      let checkedCount = 0
      this[datakey][portIndex].List.map((item) => {
        if (item.checked) {
          checkedCount++
        }
      })
      this[datakey][portIndex].checked =
        checkedCount === this[datakey][portIndex].List.length
      this[datakey][portIndex].isIndeterminate =
        checkedCount > 0 && checkedCount < this[datakey][portIndex].List.length
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      console.log(this.queryParams)
      let params = { ...this.queryParams }
      params.startTime = params.date[0]
      params.endTime = params.date[1]
      delete params.date
      console.log(params)
      listPost_notice(params).then((response) => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
        this.postList.map((item) => {
          item.roleIds = item.roleIds.split(',')

          let receiverList = []
          if (
            item.roleIds.find((item) => {
              return item == '5'
            })
          ) {
            receiverList.push('教务平台')
          }
          if (
            item.roleIds.find((item) => {
              return item == '3'
            })
          ) {
            receiverList.push('教师端')
          }
          if (
            item.roleIds.find((item) => {
              return item == '4'
            })
          ) {
            receiverList.push('学生端')
          }
          console.log(receiverList)
          item.receiverList = receiverList.join(',')
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeContent: undefined,
        startTime: '',
        endTime: '',
        noticeType: 2,
        receiverList: undefined,
        publishStatus: true,
        readStatus: false,
        remark: '',
        status: '',
        noticeStatus: ''
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.schoolId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 跳转
      this.$router.push({
        path: '/announcement/addAnnouncementManagement',
        query: {
          type: 'add'
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      if (type == 'detail') {
        this.$router.push({
          path: '/announcement/previewAnnouncementManagement',
          query: {
            type: type,
            id: row.noticeId
          }
        })
      } else {
        this.$router.push({
          path: '/announcement/addAnnouncementManagement',
          query: {
            type: type,
            id: row.noticeId
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      let arr = []
      //提交的时候处理端口
      this.ports.map((port) => {
        port.List.map((role) => {
          if (role.checked) {
            arr.push({
              roleId: role.roleId,
              keyName: role.keyName,
              status: role.status,
              type: role.type
            })
          }
        })
      })
      // 提交的时候处理角色
      this.roles.map((role) => {
        if (role.checked || role.isIndeterminate) {
          let branchIds = []
          role.List.map((item) => {
            if (item.checked) {
              branchIds.push(item.branchId)
            }
          })
          arr.push({
            roleId: role.roleId,
            keyName: role.keyName,
            status: role.status,
            type: role.type,
            branchIds: branchIds.join(',')
          })
        }
      })
      this.form.receiverList = arr
      if (
        this.timePickerUse &&
        new Date(this.form.startTime).getTime() < new Date().getTime()
      ) {
        this.$modal.msg('显示时间必须大于当前时间')
        return false
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let data = { ...this.form }
          data.startTime = this.timePickerUse ? this.form.startTime : null
          if (this.form.noticeId != undefined) {
            data.noticeStatus = type == 'add' ? 1 : 0
            data.publishStatus = type == 'add'
            updatePost_notice(data).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            data.noticeStatus = type == 'add' ? 1 : 0
            data.publishStatus = type == 'add'
            addPost_notice(data).then(() => {
              this.$modal.msgSuccess(type == 'add' ? '发送成功' : '保存成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeId = row.noticeId || this.ids

      this.$confirm(
        `确认删除【${row.noticeTitle}】吗？删除后不可恢复`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          await delPost_notice(noticeId)
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /* 下架操作 */
    handleTakedown(item) {
      this.$confirm(
        `确定撤销【${item.noticeTitle}】吗？撤销后可重新编辑`,
        '撤销确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          await changePublishStatus({
            isPublish: false,
            noticeId: item.noticeId,
            publishStatus: false,
            noticeStatus: 0,
            noticeType: 2
          })
          this.getList()
          this.$modal.msgSuccess('撤销成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/post/export',
        {
          ...this.queryParams
        },
        `post_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-menu-item:hover {
  border-bottom: 1px solid #e6e6e6 !important;
}

::v-deep .el-menu--horizontal > .el-menu-item.is-active:hover {
  border-bottom: 2px solid #11a983 !important;
}
</style>
